﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.International.Converters.PinYinConverter;
using System.Net;
using System.Threading;
namespace WinUserAcc
{
    public partial class frmUserAcc : Form
    {
        public frmLogin login;
        private bool isExit = true;

        public string UserName;
        public string Pwd;
        private string _companyPath = "";

        //在程序的生存期内不发生更改的不可变值
        public const string PROTOCOL = "LDAP://";

        public readonly string CONGIGURATION;
        public frmUserAcc()
        {

            InitializeComponent();
            CONGIGURATION = Common.Domain;

        }

        #region 添加用户

        /// <summary>
        /// 添加用户
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripLabel1_Click(object sender, EventArgs e)
        {
            var pinyin = txtAccount.Text.Trim();
            var inputName = txtFirstName.Text.Trim() + txtSecondName.Text.Trim();


            if (Verify(pinyin))
            {

                try
                {
                    DataGridViewRow dgvRow = null;
                    if (gbox.Text == "修改")
                    {
                        dgvRow = dgvUserInfo.Tag as DataGridViewRow;
                        gbox.Text = "域用户基本信息";
                        toolStripLabel1.Text = "添加";
                        toolStripLabel2.Enabled = true;
                        toolStripButton2.Enabled = true;
                    }
                    else
                    {
                        var index = this.dgvUserInfo.Rows.Add();
                        dgvRow = dgvUserInfo.Rows[index];
                    }
                    dgvRow.Cells["uname"].Value = inputName;//姓名
                    dgvRow.Cells["uno"].Value = txtNo.Text;
                    dgvRow.Cells["firstname"].Value = txtFirstName.Text;
                    dgvRow.Cells["secondname"].Value = txtSecondName.Text;

                    dgvRow.Cells["account"].Value = pinyin; //账户
                    dgvRow.Cells["desc"].Value = txtNo.Text.Trim().ToUpper() + txtFirstName.Text.Trim() +
                                                             txtSecondName.Text.Trim();//描述
                    var node = cbtOU.SelectedNode;
                    if (node != null && !string.IsNullOrEmpty(node.Text.Trim()))
                    {
                        dgvRow.Cells["ou"].Value = node.Text;//组织单位
                    }

                    dgvRow.Cells["department"].Value = txtDepartment.Text.Trim();//部门
                    dgvRow.Cells["selectedNode"].Value = node;
                    dgvRow.Cells["title"].Value = txtDuty.Text;//职位
                    dgvRow.Cells["userprincipalname"].Value = pinyin + "@" + CONGIGURATION + ".com.cn";//用户登录名
                    dgvRow.Cells["company"].Value = lblCurrentCompany.Text;//公司
                    dgvRow.Cells["sn"].Value = txtFirstName.Text.Trim();//姓
                    dgvRow.Cells["givename"].Value = txtSecondName.Text.Trim();//名
                    dgvRow.Cells["displayname"].Value = txtNo.Text.Trim().ToUpper() + txtFirstName.Text.Trim() +
                                                              txtSecondName.Text.Trim();//显示名称
                    dgvRow.Cells["mail"].Value = pinyin + "@" + CONGIGURATION + ".com.cn";
                    dgvRow.Cells["startupMail"].Value = chkMailBox.Checked;

                    dgvRow.Cells["password"].Value = chkDefault.Checked
                        ? ConfigurationManager.AppSettings["defaultPwd"]
                        : txtPwd.Text;
                    dgvRow.Cells["mustChangePwd"].Value = chkPwd.Checked;
                    dgvRow.Cells["isCommunications"].Value = chkCommunications.Checked;
                    dgvRow.Cells["deptPath"].Value = PROTOCOL + CONGIGURATION + "/" + node.Tag;
                    dgvRow.Cells["selectedGroupNames"].Value = pcbGroups.Text;
                    var groups = pcbGroups.Text.Replace(" ", "").Split(',');
                    if (pcbGroups.Text.Replace(" ", "") != "" && groups.Any())
                    {
                        dgvRow.Cells["memberOf"].Value = groups[0] + "等"; //隶属于
                    }
                    else
                    {
                        dgvRow.Cells["memberOf"].Value = "";
                    }

                    for (var i = 0; i < dgvUserInfo.Rows.Count; i++)
                    {
                        dgvUserInfo.Rows[i].Cells[0].Value = i + 1;
                    }

                    var groupPathList = new List<string>();
                    foreach (string g in groups)
                    {
                        if (pcbGroups.Tag == null) return;
                        var olist = pcbGroups.Tag as List<object>;
                        for (var i = 0; i < olist.Count; i++)
                        {
                            var o = olist[i];
                            if (g.Trim() == o.GetType().GetProperty("gname").GetValue(o).ToString())
                            {
                                groupPathList.Add(o.GetType().GetProperty("gpath").GetValue(o).ToString());
                            }
                        }

                    }
                    dgvRow.Cells["memberOfValues"].Value = groupPathList;
                }
                catch (Exception ex)
                {

                    Console.WriteLine(ex.Message);
                }

            }

        }
        #endregion

        #region  删除用户
        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripLabel2_Click(object sender, EventArgs e)
        {
            int k = dgvUserInfo.SelectedRows.Count;
            if (k > 0)
            {
                DialogResult RSS = MessageBox.Show(this, "你确定要删除" + Convert.ToString(k) + "个对象吗？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
                switch (RSS)
                {
                    case DialogResult.OK:
                        for (int i = this.dgvUserInfo.SelectedRows.Count; i > 0; i--)
                        {
                            int ID = Convert.ToInt32(dgvUserInfo.SelectedRows[i - 1].Cells[0].Value);
                            dgvUserInfo.Rows.RemoveAt(dgvUserInfo.SelectedRows[i - 1].Index);//从集合中删除选中的行

                        }
                        break;
                    case DialogResult.Cancel:
                        break;
                }
            }

            for (var i = 0; i < dgvUserInfo.Rows.Count; i++)
            {
                dgvUserInfo.Rows[i].Cells[0].Value = i + 1;
            }

        }
        #endregion

        #region 修改用户信息

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            var row = dgvUserInfo.CurrentRow;
            dgvUserInfo.Tag = row;
            if (row != null)
            {
                gbox.Text = "修改";
                toolStripLabel1.Text = "保存";
                toolStripLabel2.Enabled = false;
                toolStripButton2.Enabled = false;
                txtNo.Text = row.Cells["uno"].Value.ToString();
                txtFirstName.Text = row.Cells["firstname"].Value.ToString();
                txtSecondName.Text = row.Cells["secondname"].Value.ToString();
                txtAccount.Text = row.Cells["account"].Value.ToString();
                txtDepartment.Text = row.Cells["department"].Value.ToString();
                txtDuty.Text = row.Cells["title"].Value.ToString();
                if (row.Cells["password"].ToString() == ConfigurationManager.AppSettings["defaultPwd"])
                {
                    txtPwd.Visible = false;
                    chkDefault.Checked = true;
                }
                else
                {
                    txtPwd.Visible = true;
                    chkDefault.Checked = false;
                    txtPwd.Text = row.Cells["password"].Value.ToString();
                }
                chkPwd.Checked = Convert.ToBoolean(row.Cells["mustChangePwd"].Value);

                cbtOU.SelectedNode = row.Cells["selectedNode"].Value as TreeNode;
                cbtOU_Leave(null, null);
                pcbGroups.Text = row.Cells["selectedGroupNames"].Value.ToString();
            }
        }

        #endregion

        #region 清空dgvUserInfo数据
        /// <summary>
        /// 清空dgvUserInfo数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            int k = dgvUserInfo.SelectedRows.Count;
            if (k > 0)
            {
                DialogResult result = MessageBox.Show("你确定要清空对象吗？", "提示", MessageBoxButtons.OKCancel,
                    MessageBoxIcon.Warning);
                if (result == DialogResult.OK)
                {

                    this.dgvUserInfo.Rows.Clear(); //清空数据

                    dgvUserInfo.Refresh();
                }
                else
                {
                    result = DialogResult.Cancel;
                }
            }

        }

        #endregion


        #region 批量创建用户账号 （按钮）
        /// <summary>
        /// 创建按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btmFound_Click(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;

            pgb.Visible = true;
            pgb.Maximum = dgvUserInfo.RowCount;

            bool result = true;
            foreach (DataGridViewRow row in dgvUserInfo.Rows)
            {
                result = result && CreateUserWithRow(row);

                pgb.Value++;
            }

            this.Cursor = Cursors.Default;
            pgb.Value = 0;
            pgb.Visible = false;
            int k = dgvUserInfo.SelectedRows.Count;
            if (k > 0&&result)
            {
                MessageBox.Show("创建成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.None);
                this.dgvUserInfo.Rows.Clear(); //创建成功后，清空dgvUserInfo里所有信息。
            }
        }

        private bool CreateUserWithRow(DataGridViewRow row)
        {
            var exceptions = new List<Exception>();

            var _uname = row.Cells["uname"].Value;
            var _account = row.Cells["account"].Value;
            var _desc = row.Cells["desc"].Value;
            var _department = row.Cells["department"].Value;
            var _title = row.Cells["title"].Value;
            var _userprincipalname = row.Cells["userprincipalname"].Value;
            var _company = row.Cells["company"].Value;
            var _sn = row.Cells["sn"].Value;
            var _givename = row.Cells["givename"].Value;
            var _displayname = row.Cells["displayname"].Value;
            var _mail = row.Cells["mail"].Value;
            var _pwd = row.Cells["password"].Value;
            var _mustChangePwd = Convert.ToBoolean(row.Cells["mustChangePwd"].Value);
            var _deptPath = row.Cells["deptPath"].Value;
            var _memberOf = row.Cells["memberOfValues"].Value as List<string>;
            var isStartupMail = Convert.ToBoolean(row.Cells["startupMail"].Value); //邮箱
            var isCommunicationsServer = Convert.ToBoolean(row.Cells["isCommunications"].Value); //Communications Server 启用



            var entry = new DirectoryEntry(_deptPath.ToString(), UserName, Pwd, AuthenticationTypes.Secure);
            var ude = entry.Children.Add("CN=" + _uname, "user");

            //创建域用户所有信息添加到对应的ad活动目录中
            ude.Properties["sAMAccountName"].Value = _account;
            ude.Properties["displayname"].Value = _displayname;
            ude.Properties["description"].Value = _desc;
            ude.Properties["userPrincipalName"].Value = _userprincipalname;
            ude.Properties["Department"].Value = _department;
            ude.Properties["Company"].Value = _company;
            ude.Properties["sn"].Value = _sn;
            ude.Properties["Givenname"].Value = _givename;
            ude.Properties["Displayname"].Value = _displayname;
            ude.Properties["Mail"].Value = _mail;
            ude.Properties["Title"].Value = _title;

            try
            {
                ude.CommitChanges();

                ude.Invoke("SetPassword", new object[] { _pwd.ToString() }); //通过ad的Invoke方法把确认密码保存到账号

                ude.CommitChanges();

                ude.Properties["useraccountcontrol"].Value = 512; //普通账户
                if (_mustChangePwd)
                {
                    ude.Properties["pwdLastSet"].Clear();
                    ude.Properties["pwdlastset"].Add(0);
                }

                ude.CommitChanges();

                //添加到组

                if (_memberOf != null)
                {
                    foreach (string s in _memberOf)
                    {
                        var group = new DirectoryEntry(PROTOCOL + CONGIGURATION + "/" + s, UserName, Pwd,
                            AuthenticationTypes.Secure);
                        group.Properties["member"].Add(ude.Properties["distinguishedname"].Value);
                        group.CommitChanges();
                    }
                }
            }
            catch (Exception ex)
            {
                exceptions.Add(ex);
            }
            ude.Close();

            #region 邮箱
            try
            {
                if (isStartupMail)
                {
                    var mailInfo = new MailInfo()
                    {
                        Alias = _account.ToString(), //'别名
                        SamAccountName = _account.ToString(), //要启用邮箱的账号
                    };

                    MailManager.EnableMail(UserName, Pwd, mailInfo); //启用邮箱
                }
            }
            catch (Exception ex)
            {
                exceptions.Add(ex);
            }
            #endregion

            if (exceptions.Count > 0)
            {
                var msg = new StringBuilder();
                exceptions.ForEach(ex => msg.AppendLine(">" + ex.Message));
                MessageBox.Show(string.Format("账户{0操作失败!\n{1}", _account, msg));
                return false;
            }
            return true;
        }

        #endregion


        #region
        //#region 根据域名、用户名、密码获取sub_company_name指定的所有组
        ///// <summary>
        ///// 根据域名、用户名、密码获取sub_company_name指定的所有组
        ///// </summary>
        ///// <param name="domain"></param>
        ///// <param name="adusername"></param>
        ///// <param name="adpassword"></param>
        ///// <returns></returns>
        //public DirectoryEntries GetADGroups(string adusername, string adpassword)
        //{
        //    try
        //    {
        //        var entry =
        //            new DirectoryEntry(string.Format(PROTOCOL + CONGIGURATION + "/OU=AL.南京中原,OU=中原地产,DC=" + CONGIGURATION + ",DC=com,DC=cn"),
        //                adusername, adpassword);
        //        entry.RefreshCache();


        //        var search = new DirectorySearcher(entry);

        //        //search.Filter = ("(objectClass=group)");
        //        search.Filter = ("(objectClass=organizationalUnit)");
        //        //search.Filter = ("(objectCategory=group)");
        //        // search.Filter = ("(objectCategory=group)");
        //        //search.Sort = new SortOption("samaccountname", SortDirection.Ascending);
        //        search.SearchScope = SearchScope.Subtree;

        //        var one = search.FindAll();

        //        #region ous

        //        //var writer = new StreamWriter("ous.txt");
        //        //for (var i = 0; i < one.Count; i++)
        //        //{
        //        //    writer.WriteLine(one[i].GetDirectoryEntry().Path);
        //        //}
        //        //writer.Close();

        //        #endregion



        //        // var newEntry = one[0].GetDirectoryEntry();

        //        //var one = search.FindOne();

        //        //var newEntry = one.GetDirectoryEntry();
        //        //return newEntry.Children;
        //        return null;

        //    }
        //    catch (Exception ex)
        //    {
        //        Console.WriteLine("ERROR:" + ex.Message);
        //        return null;
        //    }
        //}
        //#endregion
        #endregion

        #region 输出SearchResult对象的所有属性名及属性值到控制台

        /// <summary>
        /// 输出SearchResult对象的所有属性名及属性值到控制台
        /// </summary>
        /// <param name="de"></param>
        private void WriteProperties(SearchResult de)
        {
            if (de == null) return;
            var properties = de.Properties;
            var count = 1;
            foreach (DictionaryEntry p in properties)
            {
                Console.Write(count + ".  " + p.Key + ":");
                foreach (var v in (p.Value as ResultPropertyValueCollection))
                {
                    Console.WriteLine(v);

                }
                count++;
            }
        }
        #endregion

        #region 窗体加载事件
        private void frmUserAcc_Load(object sender, EventArgs e)
        {
            InitCurrentCompany();

            cbtOU.Nodes.Add(GetAll());

        }
        #endregion

        #region 根据登录用户身份确定所属公司
        /// <summary>
        /// 根据用户身份确定所属公司
        /// </summary>
        private void InitCurrentCompany()
        {

            var entry = new DirectoryEntry(PROTOCOL + CONGIGURATION, UserName, Pwd);
            var searcher = new DirectorySearcher(entry);
            searcher.Filter = "(sAMAccountName=" + UserName + ")";
            var result = searcher.FindOne(); //执行搜索并只返回找到的第一项
            lblCurrentCompany.Text = result.Properties["company"][0].ToString();
            var distinguishedname = result.Properties["distinguishedname"][0].ToString();
            var _a = distinguishedname.Split(',');
            var _b = new List<String>();
            for (var m = _a.Length - 5; m < _a.Length; m++)
            {
                _b.Add(_a[m]);
            }
            _companyPath = PROTOCOL + CONGIGURATION + "/" + string.Join(",", _b);

        }
        #endregion


        #region 把组织单元和用户节点捆绑到Treeview中
        /// <summary>
        /// 把组织单元和用户节点捆绑到Treeview中
        /// </summary>
        /// <returns></returns>
        public TreeNode GetAll()
        {
            try
            {
                var rootText = _companyPath.Split(',')[0].Substring(20);//根节点文本
                var rootNode = new TreeNode { Text = rootText, Tag = _companyPath.Substring(17) };//子节点文本
                var entry = new DirectoryEntry(_companyPath, UserName, Pwd);
                var mySearcher = new DirectorySearcher(entry) { Filter = "(objectClass=organizationalUnit)" };
                var results = mySearcher.FindAll();

                //將 LINQ 的查询字串转换成符合 RFC 2254 规格的 LDAP 查询过滤字串，再传送到 DirectorySearcher 物件中执行搜寻
                var list = (from SearchResult result in results select result.GetDirectoryEntry()).ToList();

                AddSubNode(rootNode, list);
                return rootNode;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            return null;
        }


        /// <summary>
        /// 将子节点相对应的根节点使用递归一层一层添加到树中
        /// </summary>
        /// <param name="parentNode">父节点</param>
        /// <param name="results">集合</param>

        private void AddSubNode(TreeNode parentNode, List<DirectoryEntry> results)
        {
            for (var i = 0; i < results.Count; i++)
            {
                try
                {
                    var directoryEntry = results[i];
                    var distinguishedname = directoryEntry.Properties["distinguishedname"].Value.ToString();
                    var pOU = distinguishedname.Substring(distinguishedname.Split(',')[0].Length + 1);
                    if (pOU == parentNode.Tag.ToString())
                    {

                        var subNode = new TreeNode()
                        {
                            Text = distinguishedname.Split(',')[0].Substring(3),
                            Tag = distinguishedname
                        };
                        parentNode.Nodes.Add(subNode);
                        AddSubNode(subNode, results);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    throw ex;
                }

            }
        }
        #endregion

        #region 添加用户快捷事件
        /// <summary>
        /// 回车事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAddTemp_Click(object sender, EventArgs e)
        {
            toolStripLabel1_Click(null, null);
        }

        #endregion

        #region 非空及用户名是否已存在的验证
        /// <summary>
        /// 文本验证
        /// </summary>
        public bool Verify(string account)
        {
            //如果编号为空

            #region 非空

            if (this.txtNo.Text == "")
            {

                //弹出提示信息"编号不能为空!"

                MessageBox.Show("编号不能为空!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

                this.txtNo.Focus(); //使编号文本框获得焦点

                return false; //跳出方法

            }

            //如果姓为空

            if (this.txtFirstName.Text == "")
            {

                //弹出提示信息"姓不能为空!"

                MessageBox.Show("姓不能为空!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

                this.txtFirstName.Focus(); //使姓文本框获得焦点

                return false; //跳出方法

            }

            //如果名为空

            if (this.txtSecondName.Text == "")
            {

                //弹出提示信息"名不能为空!"

                MessageBox.Show("名不能为空!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

                this.txtSecondName.Focus(); //使名文本框获得焦点

                return false; //跳出方法

            }

            //如果部门为空                                    













































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































            if (this.txtDepartment.Text == "")
            {

                //弹出提示信息"部门不能为空!"

                MessageBox.Show("部门不能为空!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

                this.txtDepartment.Focus(); //使部门文本框获得焦点

                return false; //跳出方法

            }

            //如果职务为空

            if (this.txtDuty.Text == "")
            {

                //弹出提示信息"职务不能为空!"

                MessageBox.Show("职务不能为空!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

                this.txtDuty.Focus(); //使职务文本框获得焦点

                return false; //跳出方法

            }

            //如果组织单位为空

            if (this.cbtOU.SelectedNode.Text.Trim() == "")
            {

                //弹出提示信息"组织单位不能为空!"

                MessageBox.Show("组织单位不能为空!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

                this.cbtOU.Focus(); //使组织单位文本框获得焦点

                return false; //跳出方法

            }
            #endregion

            #region 验证密码

            if ((!chkDefault.Checked))
            {
                if (txtPwd.Text == "")
                {
                    MessageBox.Show("密码不能为空!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

                    this.txtPwd.Focus();

                    return false;
                }
                /**
                 *一， 密码最少长度为 6位 ，并至少包含3种复杂类别的字符 （如 Abc134 或者 abc12# 符合 如abc123 123 <>( 就不符合） 
                二  密码最少长度为 8位 ，并至少包含2种复杂类别的字符 （如 Abc21334 或者 abcd1234 符合 如12345678 abcdefg就不符合） 
                三， 密码的复杂类别由拉丁、西里尔或希腊字母组成 
                复杂类别说明 
                1 大写字母 如:A B C....Z 
                2 小写字母 如:a b c....z 
                3 西文阿拉伯数据 如:0 1 2...9 
                4 其他字符(“特殊字符”、标点、符号 如：{ } [] , < > @ $ % & ^ ( ) _ + =  
                 **/
                else
                {
                    var reg =
                        new Regex(
                            "^(?:(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])|(?=.*[A-Z])(?=.*[a-z])(?=.*[^A-Za-z0-9])|(?=.*[A-Z])(?=.*[0-9])(?=.*[^A-Za-z0-9])|(?=.*[a-z])(?=.*[0-9])(?=.*[^A-Za-z0-9])).{6,}|(?:(?=.*[A-Z])(?=.*[a-z])|(?=.*[A-Z])(?=.*[0-9])|(?=.*[A-Z])(?=.*[^A-Za-z0-9])|(?=.*[a-z])(?=.*[0-9])|(?=.*[a-z])(?=.*[^A-Za-z0-9])|(?=.*[0-9])(?=.*[^A-Za-z0-9])|).{8,}");
                    var pwd = txtPwd.Text;
                    if (!reg.IsMatch(pwd))
                    {
                        MessageBox.Show("密码复杂度不够!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

                        this.txtPwd.Focus();

                        return false;
                    }
                }
            }

            #endregion

            var flag = false;//是否已存在
            if (gbox.Text != "修改")
            {
                //验证DataGridview中是否已添加
                foreach (DataGridViewRow row in dgvUserInfo.Rows)
                {
                    if (row.Cells["account"].Value.ToString() == account)
                    {
                        flag = true;
                        break;
                    }
                }
            }
            //验证AD中用户是否已存在
            var entry = new DirectoryEntry(PROTOCOL + CONGIGURATION);
            var searcher = new DirectorySearcher(entry);
            searcher.Filter = "(sAMAccountName=" + account + ")";
            var result = searcher.FindOne();
            if ((result != null) || flag)
            {
                MessageBox.Show("已存在同名账号!", "提示", MessageBoxButtons.OK, MessageBoxIcon.None);
                txtFirstName.Text = "";
                txtSecondName.Text = "";
                return false;

            }
            return true;
        }

        #endregion



        #region  文本变化时将自动生成的账号即时显示

        private void txtFirstName_TextChanged(object sender, EventArgs e)
        {
            var pinyin = string.Empty;
            var inputName = txtFirstName.Text.Trim() + txtSecondName.Text.Trim();
            foreach (char c in inputName)
            {
                try
                {
                    if (c > 127)//在 ASCII码表中，英文的范围是0-127，而汉字则是大于127
                    {
                        var chineseChar = new ChineseChar(c);
                        pinyin += chineseChar.Pinyins[0].Substring(0, chineseChar.Pinyins[0].Length - 1).ToLower();
                    }
                    else
                    {
                        pinyin += c;
                    }

                }
                catch (Exception)
                {
                    pinyin += c;
                }
            }

            txtAccount.Text = pinyin;
        }

        private void txtSecondName_TextChanged(object sender, EventArgs e)
        {
            var pinyin = string.Empty;
            var inputName = txtFirstName.Text.Trim() + txtSecondName.Text.Trim();
            foreach (char c in inputName)
            {
                try
                {
                    if (c > 127)//在 ASCII码表中，英文的范围是0-127，而汉字则是大于127
                    {
                        var chineseChar = new ChineseChar(c);
                        pinyin += chineseChar.Pinyins[0].Substring(0, chineseChar.Pinyins[0].Length - 1).ToLower();
                    }
                    else
                    {
                        pinyin += c;
                    }

                }
                catch (Exception)
                {
                    pinyin += c;
                }
            }

            txtAccount.Text = pinyin;
        }

        #endregion


        #region 加载隶属于组
        private void cbtOU_Leave(object sender, EventArgs e)
        {
            pcbGroups.Text = "";
            pcbGroups.Items.Clear();
            txtSecondName.Text.Trim();//描述
            var node = cbtOU.SelectedNode;
            if (node != null && !string.IsNullOrEmpty(node.Text.Trim()))
            {
                var path = PROTOCOL + CONGIGURATION + "/" + node.Tag; //所选的组织单元的ad路径
                var entry = new DirectoryEntry(path, UserName, Pwd, AuthenticationTypes.Secure);
                var search = new DirectorySearcher(entry);
                search.Filter = "(objectClass=group)";
                var results = search.FindAll();
                var entryList = (from SearchResult result in results select result.GetDirectoryEntry()).ToList();
                var itemList = new List<object>();
                foreach (DirectoryEntry de in entryList)
                {
                    var groupName = de.Properties["name"].Value.ToString();
                    var groupPath = de.Properties["distinguishedname"].Value.ToString();
                    var item = new
                    {
                        gname = groupName,
                        gpath = groupPath
                    };
                    itemList.Add(item);
                }
                if (itemList.Count == 0) return;
                //pcbGroups.DataSource = itemList;
                //pcbGroups.DisplayMember = "gname";
                //pcbGroups.ValueMember = "gpath";
                pcbGroups.Tag = itemList;
                foreach (object o in itemList)
                {
                    pcbGroups.Items.Add(o.GetType().GetProperty("gname").GetValue(o));
                }

            }
        }
        #endregion



        #region 用户关闭窗体做出退出整个程序

        /// <summary>
        /// 当用户关闭窗体做出退出整个程序
        /// </summary>r
        /// <param name="sender"></param>
        /// <param name="e"></param>

        private void frmUserAcc_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (isExit)
            {
                DialogResult result = MessageBox.Show("是否退出？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                if (result == DialogResult.No)
                {
                    e.Cancel = true;
                    return;
                }
                this.Dispose();
                Application.ExitThread();
            }
        }
        ///<summary>
        ///退出程序
        ///</summary>
        ///<param name="sender"></param>
        ///<param name="e"></param>
        private void btnExit_Click(object sender, EventArgs e)
        {
            this.Close(); //退出整个程序
        }
        #endregion


        #region ‘默认密码’更改事件
        /// <summary>
        /// ‘默认密码’更改事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void chkDefault_CheckedChanged(object sender, EventArgs e)
        {
            //如果选中
            if (chkDefault.Checked)
            {
                txtPwd.Visible = false;//禁止输入在文本中
            }
            else
            {
                txtPwd.Visible = true;
                txtPwd.Enabled = true;
                txtPwd.Text = "";
            }
        }
        #endregion

        #region ‘用户下次登录时须更改密码’更改事件

        /// <summary>
        /// ‘用户下次登录时须更改密码’更改事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void chkPwd_CheckedChanged(object sender, EventArgs e)
        {
            //如果 选中
            if (chkPwd.Checked)
            {

            }
        }


        #endregion



        private void cbtOU_OnSelectedNodeChanged(object sender, ComboTree.TreeNodeSelectedNodeChangedEventArgs e)
        {
            pcbGroups.Text = "";
            pcbGroups.Items.Clear();
        }

        #region 注销事件
        private void btnCancel_Click(object sender, EventArgs e)
        {
            isExit = false;
            this.Close();
            login.Show();
        }
        #endregion

    }
}
